<template>
    <div class="container">
        <div class="left-side">
            <el-menu :default-active="activeMenu" class="center-menu" @select="handleSelect">
                <el-menu-item index="my-blogs">
                    <el-icon>
                        <Document />
                    </el-icon>
                    <span>我的博客</span>
                </el-menu-item>
                <el-menu-item index="my-drafts">
                    <el-icon>
                        <EditPen />
                    </el-icon>
                    <span>我的草稿</span>
                </el-menu-item>
                <el-menu-item index="my-likes">
                    <el-icon>
                        <Star />
                    </el-icon>
                    <span>我的点赞</span>
                </el-menu-item>
                <el-menu-item index="my-comments">
                    <el-icon>
                        <ChatDotRound />
                    </el-icon>
                    <span>我的评论</span>
                </el-menu-item>
                <el-menu-item index="my-follows">
                    <el-icon>
                        <UserFilled />
                    </el-icon>
                    <span>我的关注</span>
                </el-menu-item>
                <el-menu-item index="my-fans">
                    <el-icon>
                        <User />
                    </el-icon>
                    <span>我的粉丝</span>
                </el-menu-item>
                <el-menu-item index="my-settings">
                    <el-icon>
                        <Setting />
                    </el-icon>
                    <span>个人设置</span>
                </el-menu-item>
            </el-menu>
        </div>

        <div class="right-side">
            <!-- 我的博客 -->
            <div v-if="activeMenu === 'my-blogs'" class="content-section">
                <div class="section-header">
                    <h2>我的博客</h2>
                    <el-button type="primary" @click="$router.push('/blog/publish')">
                        写博客
                    </el-button>
                </div>
                <el-tabs v-model="blogTab">
                    <el-tab-pane label="已发布" name="published">
                        <BlogList :blogs="publishedBlogs" />
                    </el-tab-pane>
                    <el-tab-pane label="审核中" name="reviewing">
                        <BlogList :blogs="reviewingBlogs" />
                    </el-tab-pane>
                    <el-tab-pane label="未通过" name="rejected">
                        <BlogList :blogs="rejectedBlogs" />
                    </el-tab-pane>
                </el-tabs>
            </div>

            <!-- 我的草稿 -->
            <div v-if="activeMenu === 'my-drafts'" class="content-section">
                <div class="section-header">
                    <h2>我的草稿</h2>
                </div>
                <BlogList :blogs="draftBlogs" />
            </div>

            <!-- 我的点赞 -->
            <div v-if="activeMenu === 'my-likes'" class="content-section">
                <div class="section-header">
                    <h2>我的点赞</h2>
                </div>
                <BlogList :blogs="likedBlogs" />
            </div>

            <!-- 我的评论 -->
            <div v-if="activeMenu === 'my-comments'" class="content-section">
                <div class="section-header">
                    <h2>我的评论</h2>
                </div>
                <div class="comment-list">
                    <el-card v-for="comment in comments" :key="comment.id" class="comment-item">
                        <div class="comment-content">{{ comment.content }}</div>
                        <div class="comment-meta">
                            <span>评论于：{{ comment.blogTitle }}</span>
                            <span>{{ comment.createTime }}</span>
                        </div>
                    </el-card>
                </div>
            </div>

            <!-- 我的关注 -->
            <div v-if="activeMenu === 'my-follows'" class="content-section">
                <div class="section-header">
                    <h2>我的关注</h2>
                </div>
                <div class="user-list">
                    <el-card v-for="user in follows" :key="user.id" class="user-item">
                        <div class="user-info">
                            <el-avatar :src="user.avatarUrl" />
                            <span class="username">{{ user.username }}</span>
                        </div>
                        <el-button type="primary" size="small">已关注</el-button>
                    </el-card>
                </div>
            </div>

            <!-- 我的粉丝 -->
            <div v-if="activeMenu === 'my-fans'" class="content-section">
                <div class="section-header">
                    <h2>我的粉丝</h2>
                </div>
                <div class="user-list">
                    <el-card v-for="user in fans" :key="user.id" class="user-item">
                        <div class="user-info">
                            <el-avatar :src="user.avatarUrl" />
                            <span class="username">{{ user.username }}</span>
                        </div>
                        <el-button :type="user.isFollowed ? 'primary' : 'default'" size="small">
                            {{ user.isFollowed ? '已关注' : '关注' }}
                        </el-button>
                    </el-card>
                </div>
            </div>

            <!-- 个人设置 -->
            <div v-if="activeMenu === 'my-settings'" class="content-section">
                <div class="section-header">
                    <h2>个人设置</h2>
                </div>
                <el-tabs>
                    <el-tab-pane label="基本信息">
                        <el-form :model="userForm" label-width="100px">
                            <el-form-item label="头像">
                                <el-upload class="avatar-uploader" :action="'http://localhost:91/api/file/upload'" :show-file-list="false"
                                    :on-success="handleAvatarSuccess">
                                    <img v-if="userForm.avatarUrl" :src="userForm.avatarUrl" class="avatar" />
                                    <el-icon v-else class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </el-upload>
                            </el-form-item>

                            <el-form-item label="用户名">
                                <el-input v-model="userForm.username" maxlength="20" show-word-limit />
                            </el-form-item>

                            <el-form-item label="个人简介">
                                <el-input v-model="userForm.content" type="textarea" :rows="3" maxlength="200"
                                    show-word-limit />
                            </el-form-item>

                            <el-form-item>
                                <el-button type="primary" @click="saveUserInfo">保存修改</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>

                    <el-tab-pane label="修改密码">
                        <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
                            <el-form-item label="当前密码" prop="oldPassword">
                                <el-input v-model="passwordForm.oldPassword" type="password" show-password
                                    placeholder="请输入当前密码" />
                            </el-form-item>

                            <el-form-item label="新密码" prop="newPassword">
                                <el-input v-model="passwordForm.newPassword" type="password" show-password
                                    placeholder="请输入新密码" />
                            </el-form-item>

                            <el-form-item label="确认密码" prop="confirmPassword">
                                <el-input v-model="passwordForm.confirmPassword" type="password" show-password
                                    placeholder="请再次输入新密码" />
                            </el-form-item>

                            <el-form-item>
                                <el-button type="primary" @click="changePassword" :loading="changing">
                                    修改密码
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Document, EditPen, Star, ChatDotRound, UserFilled, User, Setting, Plus } from '@element-plus/icons-vue'
import BlogList from '@/components/BlogList.vue'
import CryptoJS from 'crypto-js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { updateUserInfo } from '@/api/user'

const activeMenu = ref('my-blogs')
const blogTab = ref('published')
const router = useRouter()
const userStore = useUserStore()

// 模拟数据
const publishedBlogs = ref([])
const reviewingBlogs = ref([])
const rejectedBlogs = ref([])
const draftBlogs = ref([])
const likedBlogs = ref([])
const comments = ref([])
const follows = ref([])
const fans = ref([])

const userForm = reactive({
    id: sessionStorage.getItem('userId'),
    avatarUrl: '',
    username: '',
    bio: ''
})

const passwordFormRef = ref(null)
const changing = ref(false)
const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
    if (value !== passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

const passwordRules = {
    oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
    ]
}

const handleSelect = (key) => {
    activeMenu.value = key
}

const handleAvatarSuccess = (res) => {
    userForm.avatarUrl = res
}

const saveUserInfo = async (res) => {
    try {
        await updateUserInfo(userForm)
        ElMessage.success('保存成功')
    } catch (error) {
        ElMessage.error('保存失败:', error)
    }
}

const changePassword = async () => {
    if (!passwordFormRef.value) return

    try {
        await passwordFormRef.value.validate()
        changing.value = true

        const oldPasswordMd5 = CryptoJS.MD5(passwordForm.oldPassword).toString()
        const newPasswordMd5 = CryptoJS.MD5(passwordForm.newPassword).toString()

        await changePassword({
            oldPassword: oldPasswordMd5,
            newPassword: newPasswordMd5
        })

        ElMessage.success('密码修改成功，请重新登录')
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
        passwordFormRef.value.resetFields()

        await userStore.logout()
        router.push('/login')
    } catch (error) {
        console.error('修改密码失败:', error)
    } finally {
        changing.value = false
    }
}
</script>

<style scoped>
.container {
    display: flex;
    gap: 20px;
    padding: 20px 0;
}

.left-side {
    width: 200px;
    flex-shrink: 0;
}

.right-side {
    flex: 1;
    min-width: 0;
}

.center-menu {
    background: #fff;
    border-radius: 4px;
}

.content-section {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
        margin: 0;
        font-size: 18px;
        font-weight: 500;
    }
}

.comment-list,
.user-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.comment-item {
    .comment-content {
        margin-bottom: 8px;
    }

    .comment-meta {
        display: flex;
        justify-content: space-between;
        color: #999;
        font-size: 12px;
    }
}

.user-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;

    .user-info {
        display: flex;
        align-items: center;
        gap: 12px;
    }
}

.avatar-uploader {
    :deep(.el-upload) {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);

        &:hover {
            border-color: var(--el-color-primary);
        }
    }
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
}
</style>